﻿using System.Text.Json;
using System.Text.Json.Serialization;

namespace PropertyManagementWebApi.Extensions
{
    public class GuidConverter : JsonConverter<Guid?>
    {
        public override Guid? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            if (reader.TokenType == JsonTokenType.Null)
                return null;

            if (reader.TokenType == JsonTokenType.String)
            {
                string? value = reader.GetString();
                // 关键处理：空字符串转换为null
                if (string.IsNullOrEmpty(value))
                    return null;

                if (Guid.TryParse(value, out Guid guid))
                    return guid;
            }

            throw new JsonException("Invalid GUID format.");
        }

        // Write方法保持不变
        public override void Write(Utf8JsonWriter writer, Guid? value, JsonSerializerOptions options)
        {
            if (value.HasValue)
                writer.WriteStringValue(value.Value.ToString());
            else
                writer.WriteNullValue();
        }
    }
}
